package service

import (
	"backend/api"
	"backend/global"
	"backend/internal/biz"
	"backend/pkg/utils"
	"context"
	"strconv"

	"github.com/gin-gonic/gin"
)

type UserRepo interface {
	GetUserByID(id uint64) (*biz.User, error)
	Create(ctx context.Context, usr *biz.User) (*biz.User, error)
	GetUserByUserName(ctx context.Context, usrName string) (*biz.User, error)
	FindByID(ctx context.Context, id uint64) (*biz.User, error)
}

type UserService struct {
	UserRepo UserRepo
	tm       Transaction
}

// 新建userService
func NewUserService(userRepo UserRepo, tm Transaction) *UserService {
	return &UserService{UserRepo: userRepo, tm: tm}
}

func (s *UserService) Register(ctx *gin.Context, params api.RegisterAdminParams) (*biz.User, error) {
	user, _ := s.UserRepo.GetUserByUserName(ctx, params.Username)
	if user != nil {
		return nil, global.BadRequest("用户名已存在")
	}
	u, err := s.UserRepo.Create(ctx, &biz.User{
		UserName: params.Username,
		Password: utils.BcryptMake([]byte(params.Password)),
	})
	if err != nil {
		return nil, err
	}
	return u, nil
}

func (s *UserService) Login(ctx *gin.Context, userName string, password string) (*biz.User, error) {
	user, err := s.UserRepo.GetUserByUserName(ctx, userName)
	if err != nil {
		return nil, err
	}
	if user == nil || !utils.BcryptMakeCheck([]byte(password), user.Password) {
		return nil, global.BadRequest("用户名不存在或密码错误")
	}
	return user, nil
}

// GetUserInfo 获取用户信息
func (s *UserService) GetUserInfo(ctx *gin.Context, idStr string) (*biz.User, error) {
	id, err := strconv.ParseUint(idStr, 10, 64)
	if err != nil {
		return nil, global.NotFound("数据ID错误")
	}
	u, err := s.UserRepo.FindByID(ctx, id)
	if err != nil {
		return nil, global.NotFound("数据不存在", global.USER_NOT_FOUND)
	}

	return u, nil
}
